using ThingsEdge.Exchange.Contracts;

namespace Digitalmes.Application.Scada.Extensions;

public static class PayloadDataExtensions
{
    /// <summary>
    /// 提取标记对象值并转换为 double 类型，不存在或转换失败则返回 null。
    /// </summary>
    /// <param name="payloadList">数据集合</param>
    /// <param name="tagName">标记名称</param>
    /// <returns></returns>
    public static double? GetValueAsDouble(this IEnumerable<PayloadData> payloadList, string? tagName)
    {
        if (string.IsNullOrEmpty(tagName))
        {
            return default;
        }

        var payloadData = payloadList.FirstOrDefault(s => s.TagName.Equals(tagName, StringComparison.OrdinalIgnoreCase));
        if (payloadData?.TryGetAsDouble(out var v) == true)
        {
            return v;
        }

        return default;
    }

    /// <summary>
    /// 提取标记对象值并转换为 double 类型，不存在或转换失败则返回 null。
    /// </summary>
    /// <param name="payload"></param>
    /// <returns></returns>
    public static double? GetAsDouble(this PayloadData payload)
    {
        if (payload.TryGetAsDouble(out var v) == true)
        {
            return v;
        }

        return default;
    }

    /// <summary>
    /// 提取标记对象值并转换为 int32 类型，不存在或转换失败则返回 null。
    /// </summary>
    /// <param name="payloadList">数据集合</param>
    /// <param name="tagName">标记名称</param>
    /// <returns></returns>
    public static int? GetValueAsInt32(this IEnumerable<PayloadData> payloadList, string? tagName)
    {
        if (string.IsNullOrEmpty(tagName))
        {
            return default;
        }

        var payloadData = payloadList.FirstOrDefault(s => s.TagName.Equals(tagName, StringComparison.OrdinalIgnoreCase));
        if (payloadData?.TryGetAsInt32(out var v) == true)
        {
            return v;
        }

        return default;
    }
}
